import { showModal, showToast, requestPayment } from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  onShow() {
    let address = wx.getStorageSync("address");
    let cart = wx.getStorageSync("cart") || [];
    cart = cart.filter(v => v.checked)
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price
      totalNum += v.num
    });
    this.setData({ cart, totalPrice, totalNum, address })

  },
  async handleOrderPay() {
    let token = wx.getStorageSync("token");
    if (!token) {
      wx.navigateTo({
        url: '/pages/auth/index',
      });
      return
    }
    let header = { Authorization: token }
    let order_price = this.data.totalPrice
    let consignee_addr = this.data.address.provinceName + this.data.address.cityName + this.data.address.countyName + this.data.address.detailInfo
    let goods = []
    let cart = this.data.cart;
    cart.forEach(v => goods.push({
      goods_id: v.goods_id,
      goods_number: v.num,
      goods_price: v.goods_price
    }))
    let orderParams = { order_price, consignee_addr, goods }
    let { order_number } = await request({ url: '/my/orders/create', data: orderParams, method: 'POST', header })
    let { pay } = await request({ url: '/my/orders/req_unifiedorder', method: 'POST', header, data: { order_number } })
    await requestPayment(pay);
    wx.navigateTo({
      url: '/pages/order/index'
    });
  }
})